struct ListNode {
    int val;
    ListNode* next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode* next) : val(x), next(next) {}
};

class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if (head == nullptr || head->next == nullptr) {
            return head;
        }
        int len = 2;
        ListNode* tail = head->next;
        while (tail->next != nullptr) {
            len++;
            tail = tail->next;
        }
        k %= len;
        if (k > 0) {
            k = len - k;
            ListNode* tmp = head;
            while (--k > 0) {
                tmp = tmp->next;
            }
            tail->next = head;
            head = tmp->next;
            tmp->next = nullptr;
        }
        return head;
    }
};